
var fs = require("fs");
var path = require("path");
var express = require('express');
var uuid = require("./uuid");
var formidable = require('formidable');

exports.route = function(server){

    server.use("/upload",express.static(path.join(server_root,"upload")));

    server.post("/common/upload",function(req,res){
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {            
            var upload_dir = fields["upload_dir"] || "images";
            save_file(files.file,upload_dir,function(url){
                res.end("<html><head><script>"
                    +"parent."+fields["callback"]+"('"+JSON.stringify({
                        code : 1,
                        url : url
                    })+"');"
                    +"</script></head></html>");
            });
        });
    });

    
    function objForEach(obj, fn) {
        var key, result;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                result = fn.call(obj, key, obj[key])
                if (result === false) {
                    break;
                }
            }
        }
    }

    function save_file(file,upload_dir,callback){
        var extname = path.extname(file.name);
        var fileName = uuid.createShortId()+extname;

        //var upload_dir = fields["upload_dir"] || "default";
        var filepath = server_root + '/upload/' + upload_dir;

        mk_dir(server_root + '/upload/',upload_dir);

        var is = fs.createReadStream(file.path);
        var os = fs.createWriteStream(filepath + "/" + fileName);

        is.pipe(os,function(err){
            console.dir(err);
        });

        var url = "/upload/" + upload_dir +"/"+ fileName;

        is.on("end",function(){
            callback(url);
        });

        is.on("err",function(e){
            console.dir(e);
        });
    }


    server.post("/common/doc-img-upload",function(req,res){
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
            var filesurls = [],count=0;

            objForEach(files, function(name, file){ 
                count++; 
                //console.log(count);              
                save_file(file,"article-img",function(url){
                    filesurls.push(url);
                    //console.log(filesurls);      
                    if(filesurls.length == count){
                        res.json({
                            errno: 0,
                            data: filesurls
                        });
                    }
                });
            });
        });
    });
}

var mk_dir = function(root,path){
    if(!path)return;

    path = path.replace(/\\/g,"/");
    var dirs = path.split("/");

    var tpath = root;
    while(tpath && dirs.length >0){
        tpath = tpath + "/" + dirs.shift();
        if(!fs.existsSync(tpath)){
            fs.mkdirSync(tpath);
        }
    }
};